package com.jxwifi.cloud.quickclean.mycenter;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.idroid.utils.MToast;
import com.idroid.widget.CircleImageView;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.app.AccountMgr;
import com.jxwifi.cloud.quickclean.app.ClientBasicActivity;
import com.jxwifi.cloud.quickclean.app.Host;
import com.jxwifi.cloud.quickclean.app.PasswordLogin;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.bean.UploadBean;
import com.jxwifi.cloud.quickclean.login.LoginActivity;
import com.jxwifi.cloud.quickclean.order.AddRemarksActivity;
import com.jxwifi.cloud.quickclean.upgrade.UpgradeNotice;
import com.jxwifi.cloud.quickclean.utils.Constants;
import com.jxwifi.cloud.quickclean.utils.KAlertDialog;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.photo.PhotoPickerActivity;
import com.umeng.analytics.MobclickAgent;
import com.upload.BusinessModule;
import com.upload.ImgUpload;
import com.upload.UpLoadListener;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.PackageUtils;


/**
 * 个人中心
 */
public class PersonalActivity extends ClientBasicActivity implements PersonalView {


    private static final int PICK_PHOTO = 1;
    public final static int MODE_SINGLE = 0;
    @Bind(R.id.img_personal_data_photo)
    CircleImageView mImgPersonalDataPhoto;
    @Bind(R.id.et_my_personal_data_name)
    TextView mTvMyPersonalDataName;
    @Bind(R.id.et_my_personal_data_gender)
    TextView mTvMyPersonalDataGender;
    @Bind(R.id.et_my_personal_phone)
    TextView mTvMyPersonalPhone;
    @Bind(R.id.et_my_personal_versioncode)
    TextView mEtMyPersonalVersion;
    @Bind(R.id.tv_grade_name)
    TextView mTvGradeName;
    @Bind(R.id.tv_creed)
    TextView tv_creed;

    private PersonalPresenter mPersenter;

    private String PhotoUrl;

    private String mSexType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_data);
        ButterKnife.bind(this);
        openEventBus();
        mPersenter = new PersonalPresenter(mBaseContext, this);
    }

    public void initView() {
        mTvMyPersonalDataName.setText(AccountMgr.getName(mBaseContext));
        Log.i(TAG,"initView ==> VIP = "+AccountMgr.getGradeVip(mBaseContext));
        mTvGradeName.setText(AccountMgr.getGradeVip(mBaseContext));
        tv_creed.setText(AccountMgr.getpassword(mBaseContext));
        if (StateUtils.SEX_M.equals(AccountMgr.getSex(mBaseContext))) {
            mTvMyPersonalDataGender.setText("男");
        } else {
            mTvMyPersonalDataGender.setText("女");
        }
        mTvMyPersonalPhone.setText(AccountMgr.gettell(mBaseContext));
        Glide.with(mBaseContext).load(AccountMgr.getHeadImg(mBaseContext)).into(mImgPersonalDataPhoto);
        if (StateUtils.HOST_ON_LINE.equals(Host.HOST)){
            mEtMyPersonalVersion.setText("当前版本：V" + PackageUtils.getLocalVersionName(mBaseContext));
        }else{
            mEtMyPersonalVersion.setText("当前版本：V" + PackageUtils.getLocalVersionName(mBaseContext)+"(测试环境)");
        }
    }

    @OnClick({R.id.rel_img_back_pressed, R.id.rel_personal_data_photo, R.id.rel_my_personal_data_name
            , R.id.rel_my_personal_data_gender, R.id.rel_my_personal_phone, R.id.tv_sign_out_button,
              R.id.rel_my_personal_versioncode,R.id.rel_creed})
    void clickCK(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
            //头像
            case R.id.rel_personal_data_photo:
                initphone();
                MobclickAgent.onEvent(mBaseContext, "rel_personal_data_photo");
                break;
            //昵称
            case R.id.rel_my_personal_data_name:
                intent.setClass(mBaseContext, SetNameActivity.class);
                startActivity(intent);
                MobclickAgent.onEvent(mBaseContext, "rel_my_personal_data_name");
                break;
            //人生信条
            case R.id.rel_creed:
                intent.setClass(mBaseContext, AddRemarksActivity.class);
                intent.putExtra("creedFlag",1);
                startActivity(intent);
                MobclickAgent.onEvent(mBaseContext, "rel_creed");
                break;
            //性别
            case R.id.rel_my_personal_data_gender:
                mPersenter.sexChoice();
                MobclickAgent.onEvent(mBaseContext, "rel_my_personal_data_gender");
                break;
            //手机号
            case R.id.rel_my_personal_phone:
                /*intent.setClass(mBaseContext, SetPhoneActivity.class);
                startActivity(intent);
                MobclickAgent.onEvent(mBaseContext, "rel_my_personal_phone");*/
                break;
            //退出
            case R.id.tv_sign_out_button:
                mPersenter.outLogin();//退出接口请求，不做操作，现在后台没有返回的操作，只做统计。
                AccountMgr.logout(mBaseContext);
                intent.setClass(mBaseContext, LoginActivity.class);
                startActivity(intent);
                MobclickAgent.onEvent(mBaseContext, "tv_sign_out_button");
                break;
            case R.id.rel_my_personal_versioncode:
                UpgradeNotice.UpgradeData(mBaseContext, TAG, 0,this);
                break;
        }
    }


    /**
     * 图片选择回调的方法
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PHOTO) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                uploadImg(result.get(0));
            }
        }
    }

    //图片上传
    public void uploadImg(String img) {
        new ImgUpload(mBaseContext, UrlPool.STORAGE_UPLOAD, img, new UpLoadListener() {
            @Override
            public void onComplete(boolean isSuccess, String response) {

                if (isSuccess) {
                    UploadBean muploadbean = JSON.parseObject(response, UploadBean.class);
                    PhotoUrl = muploadbean.getUrl();
                    mPersenter.profile();

                } else {
                    Toaster.show(getApplicationContext(), "上传失败，请重试");
                }

            }
        }, TAG).setBusinessModule(BusinessModule.Head).doUpload();
    }

    public void initphone() {
        if (isPermissionGranted(Manifest.permission.CAMERA,
                Constants.QUEST_CODE_CAMERA)) {
            Intent intent = new Intent();
            intent.setClass(mBaseContext, PhotoPickerActivity.class);
            intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);//是否显示相机
            intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, MODE_SINGLE);//单选还是多选
            intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);//最多可选择数量
            startActivityForResult(intent, PICK_PHOTO);
        } else {
            if (Build.VERSION.SDK_INT <= 22) {
                final KAlertDialog dialog = new KAlertDialog(mBaseContext, "相机权限已关闭\", \"相机权限已被禁止，请在设置中开启");
                dialog.setRightTxt("去查看", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //前往应用详情界面
                        try {
                            Uri packUri = Uri.parse("package:" + mBaseContext.getPackageName());
                            Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packUri);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } catch (Exception e) {
                            MToast.shortToast(mBaseContext, "跳转失败");
                        }
                        dialog.dismiss();
                    }
                });
                dialog.setLeftTxt("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        }
    }

    @Override
    public CircleImageView getImageView() {
        return mImgPersonalDataPhoto;
    }

    @Override
    public String getSex() {
        return mSexType;
    }

    @Override
    public void onSex(String sextype) {
        mSexType = sextype;
    }

    @Override
    public String getUrl() {
        return PhotoUrl;
    }

    @Override
    public void onprofile() {
        PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
        if (PasswordLogin.mIsLogin) {
            mPersenter.profile();
        }
    }

    @Override
    public void onSexrequest() {
        PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
        if (PasswordLogin.mIsLogin) {
            mPersenter.onSexrequest();
        }
    }

    @Override
    public void onSuccess() {
        Toast toast = Toast.makeText(mBaseContext, "修改成功", Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
        initView();
    }

    @Override
    public void onFailure(int errorCode, String msg) {
        Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
    }

    protected boolean isPermissionGranted(String permissionName, int questCode) {
        //6.0以下系统，取消请求权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        //判断是否需要请求允许权限，否则请求用户授权
        int hasPermision = mBaseContext.checkSelfPermission(permissionName);
        if (hasPermision != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{permissionName}, questCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length == 0) {
            return;
        }
        switch (requestCode) {
            case Constants.QUEST_CODE_CAMERA:
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions,
                        grantResults);
                break;
        }
    }

}
